﻿using System;
using System.Collections.Generic;
using System.Text;
using DevExpress.ExpressApp.DC;
using DevExpress.Persistent.Base;
using DevExpress.Xpo;
using DevExpress.Persistent.Validation;
using DevExpress.ExpressApp;

namespace DomainComponents.Common {
    public enum Gender { 
        None = 0,
        Male = 1,
        Female = 2
    }
    public enum MartialStatus {
        None = 0,
        Single = 1,
        Married = 2,
        Divorced = 3,
        Widowed = 4
    }

    public class PersonValidationRules {
        public const string LastNameIsRequired = "PersonLastNameIsRequired";
    }

    [DomainComponent, XafDefaultProperty("FullName")]
    public interface IPerson {
        [Calculated(PersonLogic.FullNameExpressionDefault)]
        string FullName { get; }
        [RuleRequiredField(PersonValidationRules.LastNameIsRequired, DefaultContexts.Save)]
        string LastName { get; set; }
        string FirstName { get; set; }
        DateTime Birthday { get; set; }
        string JobTitle { get; set; }
        Gender Gender { get; set; }
        MartialStatus MartialStatus { get; set; }
        string SpouseName { get; set; }
        DateTime Anniversary { get; set; }
    }

    [DomainLogic(typeof(IPerson))]
    public class PersonLogic {
        public static void SetFullNameExpression(string expression) {
            ITypeInfo personTypeInfo = XafTypesInfo.Instance.FindTypeInfo(typeof(IPerson));
            IMemberInfo memberInfo = personTypeInfo.FindMember("FullName");
            CalculatedAttribute attribute = memberInfo.FindAttribute<CalculatedAttribute>();
            if(attribute == null) {
                memberInfo.AddAttribute(new CalculatedAttribute(expression));
            }
            else {
                if(attribute.Expression != expression) {
                    ((BaseInfo)memberInfo).RemoveAttribute(attribute);
                    memberInfo.AddAttribute(new CalculatedAttribute(expression));
                }
            }
        }
        public const string FullNameExpressionDefault = "concat(isnull(FirstName, ''), ' ', isnull(LastName, ''))";
        //public const string FullNameExpressionDefault = "concat(isnull(FirstName, ''), iif(IsNullOrEmpty(FirstName) or IsNullOrEmpty(LastName), '', ' '),  isnull(LastName, ''))";
    }
}
